package com.tycmc.common.dataaccess;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.tycmc.common.util.Property;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtil {
    private static Properties prop = new Properties();
    private static DataSource dataSource;

    static {
        try {
            prop.put(DruidDataSourceFactory.PROP_USERNAME, Property.getProperty("MySQL.username"));
            prop.put(DruidDataSourceFactory.PROP_PASSWORD, Property.getProperty("MySQL.password"));
            prop.put(DruidDataSourceFactory.PROP_URL, Property.getProperty("MySQL.url"));
            prop.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, Property.getProperty("MySQL.driverClassName"));
            prop.put(DruidDataSourceFactory.PROP_MAXACTIVE, Property.getProperty("MySQL.maxActive"));
            // 超时后回收
            prop.put(DruidDataSourceFactory.PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
                    Property.getProperty("MySQL.timeBetweenEvictionRunsMillis"));
            // 定时检测连接是否可用
            prop.put(DruidDataSourceFactory.PROP_TESTWHILEIDLE, Property.getProperty("MySQL.testWhileIdle"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            if (dataSource == null) {
                dataSource = DruidDataSourceFactory.createDataSource(prop);
            }
            conn = dataSource.getConnection();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return conn;
    }

    public static void closeConnection(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
